package edu.nuc.SQLoperation;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class SQLiteHelper extends SQLiteOpenHelper {
	final static private boolean DEBUG = true;
	final static private String TAG = "Yans-DEBUG";

	private SQLiteDatabase db = getReadableDatabase();

	public SQLiteHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, SQLConstant.DB_NAME, null, version);
		// TODO Auto-generated constructor stub
	}

	public SQLiteHelper(Context context) {
		this(context, SQLConstant.DB_NAME, null, SQLConstant.DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		if (DEBUG) {
			Log.v(TAG, "SQliteHelper_onCreate");
		}
		String createTableSQL = "CREATE TABLE IF NOT EXISTS "
				+ SQLConstant.TABLENAME + " (" + SQLConstant.ID
				+ " INTEGER PRIMARY KEY AUTOINCREMENT," + SQLConstant.SCORE
				+ " text,"+SQLConstant.MILIS_SCORE + " text, " + SQLConstant.UPSETFORMULA + " text, "
				+ SQLConstant.data + " text, " + SQLConstant.MILLIS_DATA + " text)";
		db.beginTransaction();
		db.execSQL(createTableSQL);
		db.setTransactionSuccessful();
		db.endTransaction();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		if (DEBUG) {
			Log.v(TAG, "SQliteHelper_onUpdate");
		}
		// TODO Auto-generated method stub

	}
	
	public void delete(long _id){
		if (DEBUG) {
			Log.v(TAG, "SQliteHelper_delete_item");
		}
		String whereClause = "_id=?";
		String[] whereArgs = { String.valueOf(_id) };
		if (db != null) {
			db.beginTransaction();
			db.delete(SQLConstant.TABLENAME, whereClause, whereArgs);
			db.setTransactionSuccessful();
			db.endTransaction();
		}
	}
	
	public boolean insert(ContentValues values) {
		if (DEBUG) {
			Log.v(TAG, "SQliteHelper_insert_item");
		}
		db.insert(SQLConstant.TABLENAME, null, values);
		return true;
	}

	public Cursor query(String orderBy) {
		if (DEBUG) {
			Log.v(TAG, "SQliteHelper_Query");
		}
		Cursor c = db.query(SQLConstant.TABLENAME, null, null, null, null,
				null, orderBy);
		return c;
	}
	
	public Cursor limitQuery(String selection,String orderBy){
		if(DEBUG){
			Log.v(TAG,"SQliteHelper_limitQuery");
		}
		Cursor c = db.query(SQLConstant.TABLENAME, null, selection, null, null, 
				null, orderBy, "10");
		return c;
	}

	public boolean deleteDatabase(Context context) {
		if (DEBUG) {
			Log.v(TAG, "SQliteHelper_deleteDatabase");
		}
		this.db.delete(SQLConstant.TABLENAME, null, null);
		return true;
	}
	public boolean closedb(){
		if (DEBUG) {
			Log.v(TAG, "SQliteHelper_closedb");
		}
		db.close();
		return true;
	}
}















